import { ElectronEventEnum } from "@enum/electron.enum";
import { type BrowserWindowConstructorOptions, app } from "electron";
import path, { join } from "path";
import { Window, WindowInstance, WindowService } from "./window";
import { getDevPort } from "@utils/common";
import { DownLoadFileService } from "./downLoad";
import { UpdateService } from "./update";
import { getAllWindows } from "@main/helper/handle";
import { useProcessException } from "@main/hooks/exception-hook";
import { Log } from './logs';
import { ShortcutService } from "./shortcut";
import { useTray } from "@main/hooks/tray-hook";
import { FileService } from "./fs";
import { PathService } from "./path";


const { renderProcessGone } = useProcessException()
const { createTray } = useTray()


export class ElectronApp {
    
  //注册外链
  static setAppProtocolClient(appName: string = "simple-electron"): void {
    let argv = [];
    //打包时不需要主文件的绝对路径 打包后已经内置（打包后process.argv只有第一个参数）
    if (!app.isPackaged) argv.push(path.resolve(process.argv[1]));
    // -- 表示后面的不再是选项 而是普通参数
    // package -t a -p -- c
    //上面表示 a为 -t命令的参数 而c是普通参数 即为 本条命令的的参数 
    argv.push("--");
    if (
      !app.isDefaultProtocolClient(appName || app.name, process.execPath, argv)
    )
      app.setAsDefaultProtocolClient(
        appName || app.name,
        process.execPath,
        argv
      );
  }

  //app单例
  static appSingle(): void {
    const gotTheLock = app.requestSingleInstanceLock();

    if (!gotTheLock) app.quit();
    else {
      app.on(ElectronEventEnum.SECOND_INSTANCE, () => {
        let main = Window.getMainWindow();
        if (main) {
          main.isMinimized() && main.restore();
          main.focus();
        }
        return;
      });
    }
  }

  //ipc
  static listenIpc():void{
     //日志
     Log.on()
     //window
     WindowService.on();
     //downLoad 
     DownLoadFileService.on();
     //更新
     UpdateService.on();
     //快捷键
     ShortcutService.on();
     //文件
     FileService.on();
     //路径
     PathService.on();
  }

  static init(
    customize: Customize,
    browserWindowOptions: BrowserWindowConstructorOptions
  ) {

    // 通过是否打包去配置初始化参数
    Window.defaultCfg = {
      defaultUrl: app.isPackaged? join(__dirname, '../../application/index.html') : `http://localhost:${getDevPort()}`,
    };

    //注册外链
    this.setAppProtocolClient();

    //单例模式
    this.appSingle();

    app.on("window-all-closed", () => {
      if (process.platform !== "darwin") app.quit();
    });

    app.whenReady().then(() => {
      process.send?.("ready");

      //应用激活后如果没有窗口则创建窗口
      app.on("activate", () => {
        if (getAllWindows().length === 0)
          WindowInstance.createWindow(customize, browserWindowOptions);
      });

      //ipc监听
      this.listenIpc()

      //渲染进程崩溃监听
      renderProcessGone()

      //创建托盘
      createTray()

      //创建渲染层
      WindowInstance.createWindow(customize, browserWindowOptions);


    });
  }
}
